package models

import (
	"context"
	"errors"
	"go-chain-api/global"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/bson/primitive"
	"go.mongodb.org/mongo-driver/mongo"
)

type UserToken struct {
	UserID       string `bson:"userId" json:"userId"`
	TokenID      string `bson:"tokenId" json:"tokenId"`
	ChainName    string `bson:"chainName" json:"chainName"`
	ChainID      int64  `bson:"chainId" json:"chainId"`
	Address      string `bson:"address" json:"address"`
	Name         string `bson:"name" json:"name"`
	Symbol       string `bson:"symbol" json:"symbol"`
	Decimals     int32  `bson:"decimals" json:"decimals"`
	TotalSupply  string `bson:"totalSupply" json:"totalSupply"`
	ApplyStatus  string `bson:"applyStatus" json:"applyStatus"` //上币申请状态 1: 申请中 2: 申请成功 3: 申请失败
	MainCoinType uint64 `bson:"mainCoinType" json:"mainCoinType"`
}

type TokenIdStr struct {
	TokenIds []string `bson:"tokenIds" json:"tokenIds"`
}

func CreateUserToken(userId string, tokenIds []string) error {
	userTokenClient := global.DBEngine.Database(global.DbConfig.DbName).Collection("user_token")
	tokenClient := global.DBEngine.Database(global.DbConfig.DbName).Collection("token")

	for _, tokenId := range tokenIds {
		err := userTokenClient.FindOne(context.TODO(), bson.M{"tokenId": tokenId, "userId": userId}).Err()
		if errors.Is(err, mongo.ErrNoDocuments) {
			var token TokenInfo
			var userToken UserToken
			objId, _ := primitive.ObjectIDFromHex(tokenId)
			err := tokenClient.FindOne(context.TODO(), bson.M{"_id": objId}).Decode(&token)
			if err != nil {
				return err
			}
			userToken.UserID = userId
			userToken.Address = token.Address
			userToken.ChainName = token.ChainName
			userToken.Decimals = int32(token.Decimals)
			userToken.Name = token.Name
			userToken.Symbol = token.Symbol
			userToken.ChainID = token.ChainID
			userToken.TotalSupply = token.TotalSupply
			userToken.TokenID = tokenId
			var scanConfig ChainConfig
			configClient := global.DBEngine.Database(global.DbConfig.DbName).Collection("scan_config")
			err = configClient.FindOne(context.TODO(), bson.M{"chainName": token.ChainName, "chainId": uint(token.ChainID)}).Decode(&scanConfig)
			if err != nil {
				return err
			}
			userToken.MainCoinType = scanConfig.UdunId
			_, err = userTokenClient.InsertOne(context.TODO(), userToken)
			if err != nil {
				return err
			}
		}
	}

	return nil
}
